package com.example.demo.zuul;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class MyGatewayFilter extends ZuulFilter {
	
		private static Logger log = LoggerFactory.getLogger(MyGatewayFilter.class);

		/*4种过滤器类型, 
		　　pre：可以在请求被路由之前调用, 
		　　route：在路由请求时候被调用, 
		　　post：在route和error过滤器之后被调用, 
		　　error：处理请求时发生错误时被调用*/ 
		@Override
		public String filterType() { 
			return "pre";
		}
		
	    @Override
	    public int filterOrder() {
	        return 0;//优先级为0，数字越大，优先级越低
	    }

	    @Override
	    public boolean shouldFilter() {
	        return true;//是否执行该过滤器，此处为true，说明需要过滤
	    }

	    @Override
	    public Object run() {
	        RequestContext ctx = RequestContext.getCurrentContext();
	        HttpServletRequest request = ctx.getRequest();

	        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));

	        String token = request.getParameter("token");//获取token参数
	        
	        System.out.println(token);
	        
//	        Object accessToken = request.getParameter("token");//获取token参数
//	        if (accessToken == null) {
//	            log.warn("token is empty");
//	            ctx.setSendZuulResponse(false);//过滤该请求, 不对其进行路由
//	            ctx.setResponseStatusCode(401);//返回错误码
//	            ctx.setResponseBody("token is null!");//返回错误内容
//	            return null;//Zuul还未对返回数据做处理
//	        }
	        return null;
	    }
	}
